/*
 结构:
 self       - 与屏幕同Bounds的半透明背景View
 bgView     - 有内容物的分享板背景
 topView    - bgView上半
 cancelBtn  - bgView下半
 */


#import "ShareView.h"
#import "ShareManager.h"
#import "ImageWithLabel.h"
#import "POP.h"

#define ScreenWidth			[[UIScreen mainScreen] bounds].size.width
#define ScreenHeight		[[UIScreen mainScreen] bounds].size.height
#define SHAREVIEW_BGCOLOR   [UIColor colorWithRed:1.00f green:1.00f blue:1.00f alpha:1]
#define WINDOW_COLOR        [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4]
#define ANIMATE_DURATION    0.25f
#define LINE_HEIGHT         75 //分享图标View高度
#define BUTTON_HEIGHT       50 //取消按钮高度
#define LABEL_HEIGHT		45 //顶部TitleView高度
#define TOP_MARGIN          10 //无Title的时候顶部Margin

@interface ShareView ()

//	所有标题
@property (nonatomic, strong) NSMutableArray  *shareBtnTitleArray;
//	所有图片
@property (nonatomic, strong) NSMutableArray  *shareBtnImageArray;
//	整个底部分享面板的 backgroundView
@property (nonatomic, strong) UIView   *bgView;
//	分享面板取消按钮上部的 View
@property (nonatomic, strong) UIView   *topSheetView;
//	取消按钮
@property (nonatomic, strong) UIButton *cancelBtn;
//	头部提示文字Label
@property (nonatomic, strong) UILabel  *proLbl;
//	头部提示文字
@property (nonatomic, copy)   NSString *protext;
//	所有的分享按钮
@property (nonatomic, copy) NSMutableArray *buttons;

@property(nonatomic,strong) UIView * backgroundView;

@end

@implementation ShareView

+ (instancetype)sharedShareBoard{
  static id instance ;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc]init];
    });
    return instance;
}


- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        
        self.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
        self.alpha = 0;
        self.backgroundColor = [WINDOW_COLOR colorWithAlphaComponent:0.4];
        self.windowLevel = UIWindowLevelAlert;
        self.userInteractionEnabled = YES;
        
        //	点击背景，收起底部分享面板，移除本视图
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tappedCancel)];
        [self addGestureRecognizer:tapGesture];
        [self makeKeyAndVisible];
        //	加载分享面板
        [self loadUIConfig];
        
    }
    return self;
}

/**
 加载自定义视图，按钮的tag依次为（200 + i）
 */
- (void)loadUIConfig {

    //添加url key之后添加
//    BOOL hadInstalledWeixin = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"weixin://"]];
//    BOOL hadInstalledQQ = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]];
//    BOOL hadInstalledWeiBo = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"weibo://"]];
    
    _shareBtnTitleArray = [NSMutableArray array];
    _shareBtnImageArray = [NSMutableArray array];
    
//    if (hadInstalledWeixin) {
        [_shareBtnTitleArray addObjectsFromArray:@[@"微信", @"微信朋友圈",@"微信收藏"]];
        [_shareBtnImageArray addObjectsFromArray:@[@"wechat",@"friend",@"wechatCollection"]];
//    }
    
//    if (hadInstalledQQ) {
        [_shareBtnTitleArray addObjectsFromArray:@[@"QQ", @"QQ空间"]];
        [_shareBtnImageArray addObjectsFromArray:@[@"qq",@"qqz"]];
//    }
    
//    if (hadInstalledWeiBo) {
        [_shareBtnTitleArray addObjectsFromArray:@[@"微博"]];
        [_shareBtnImageArray addObjectsFromArray:@[@"weibo"]];
//    }
    
    [self addSubview:self.bgView];
    [self.bgView addSubview:self.topSheetView];
    [self.bgView addSubview:self.cancelBtn];
    
    _cancelBtn.backgroundColor = _topSheetView.backgroundColor = _bgView.backgroundColor = _proLbl.backgroundColor = SHAREVIEW_BGCOLOR;
    
    //	按钮
    for (NSInteger i = 0; i < self.shareBtnTitleArray.count; i++) {
        
        CGFloat width = self.bgView.bounds.size.width / 3;
        CGFloat height = 70;
        CGFloat x = width * ( i % 3);
        CGFloat y = _proStr.length>0?LABEL_HEIGHT:TOP_MARGIN+ (i / 3) * LINE_HEIGHT;
        
        CGRect frame =  CGRectMake(x, y, width, height);
        ImageWithLabel *item = [ImageWithLabel imageLabelWithFrame:frame Image:[UIImage imageNamed:self.shareBtnImageArray[i]] LabelText:self.shareBtnTitleArray[i]];
        item.labelOffsetY = 5;
        
        item.tag = 200 + i;
        UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(itemClick:)];
        [item addGestureRecognizer:tapGes];
        [self.topSheetView addSubview:item];
        [self.buttons addObject:item];
    }
    
    [self.buttons addObject:self.cancelBtn];
    
}

- (void)show{
    
    [UIView animateWithDuration:ANIMATE_DURATION animations:^{
        
        [self.bgView setFrame:CGRectMake(0,  ScreenHeight - CGRectGetHeight(self.bgView.frame), ScreenWidth, CGRectGetHeight(self.bgView.frame))];
        self.alpha = 1;
        self.backgroundColor = [WINDOW_COLOR colorWithAlphaComponent:0.4];
    }];
    //Animation
    [self iconAnimation];
    self.visible = YES;

}

- (void)disappear{
    [self tappedCancel];
    NSLog(@"%@",self.bgView);
}


/**
 点击取消
 */
- (void)tappedCancel {
    
    [UIView animateWithDuration:ANIMATE_DURATION animations:^{
        [self.bgView setFrame:CGRectMake(0, ScreenHeight, ScreenWidth, CGRectGetHeight(self.bgView.frame))];
        self.alpha = 0;
    }];
    self.visible = NO;
  
}

/**
 做一个 icon 依次出现的弹簧动画
 */
- (void)iconAnimation {
    
    CGFloat duration = 0;
    
    for (UIView *icon in self.buttons) {
        CGRect frame = icon.frame;
        CGRect toFrame = icon.frame;
        frame.origin.y += frame.size.height;
        icon.frame = frame;
        
        POPSpringAnimation *animation = [POPSpringAnimation animationWithPropertyNamed:kPOPViewFrame];
        animation.toValue = [NSValue valueWithCGRect:toFrame];
        animation.beginTime = CACurrentMediaTime() + duration;
        animation.springBounciness = 10.0f;
        
        [icon pop_addAnimation:animation forKey:kPOPViewFrame];
        
        duration += 0.07;
    }
    
    
}

#pragma mark- Selector
- (void)dealloc{
    NSLog(@"dealloc");
}


/**
 按钮点击
 
 @param tapGes 手势
 */
- (void)itemClick:(UITapGestureRecognizer *)tapGes {
    
    ImageWithLabel* view = (ImageWithLabel*)tapGes.view;
    
    if ([self.shareViewDelegate respondsToSelector:@selector(shareTo:)]) {
        [self.shareViewDelegate shareTo:view.titleLabel.text];
    }

    [self tappedCancel];

}

#pragma mark- LazyLoad

/**
 背景View
 */
- (UIView *)bgView {
    
    if (_bgView == nil) {
        _bgView = [[UIView alloc] init];
        
        NSInteger index = _shareBtnTitleArray.count % 3 == 0?_shareBtnTitleArray.count / 3:_shareBtnTitleArray.count / 3 + 1;
        _bgView.frame = CGRectMake(0, ScreenHeight, ScreenWidth, BUTTON_HEIGHT + (_proStr.length>0?LABEL_HEIGHT:TOP_MARGIN) + LINE_HEIGHT * index);
    }
    return _bgView;
}


/**
 分享板上半部
 */
- (UIView *)topSheetView {
    if (_topSheetView == nil) {
        _topSheetView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(_bgView.frame), CGRectGetHeight(_bgView.frame) - BUTTON_HEIGHT)];
        if (_proStr.length>0) {
            [_topSheetView addSubview:self.proLbl];
        }
    }
    return _topSheetView;
}

//标题View
- (UILabel *)proLbl
{
    if (_proLbl == nil) {
        _proLbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(_bgView.frame), LABEL_HEIGHT)];
        //	默认标题
        _proLbl.text = _proStr;

        _proLbl.textAlignment = NSTextAlignmentCenter;
    }
    return _proLbl;
}

//取消按钮
- (UIButton *)cancelBtn {
    
    if (_cancelBtn == nil) {
        _cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _cancelBtn.frame = CGRectMake(0, CGRectGetHeight(_bgView.frame) - BUTTON_HEIGHT, CGRectGetWidth(_bgView.frame), BUTTON_HEIGHT);
        [_cancelBtn setTitle:NSLocalizedString(@"取消", nil) forState:UIControlStateNormal];
        [_cancelBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [_cancelBtn addTarget:self action:@selector(tappedCancel) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelBtn;
}

//按钮数组
- (NSArray *)buttons {
    if (!_buttons){_buttons = [NSMutableArray array];}
    return _buttons;
}

#pragma mark- User-Defined
- (void)setCancelBtnColor:(UIColor *)cancelBtnColor {
    [_cancelBtn setTitleColor:cancelBtnColor forState:UIControlStateNormal];
}

- (void)setProStr:(NSString *)proStr {
    _proLbl.text = proStr;
}

- (void)setOtherBtnColor:(UIColor *)otherBtnColor {
    for (id res in _bgView.subviews) {
        
        if ([res isKindOfClass:[UIButton class]]) {
            
            UIButton *button = (UIButton *)res;
            [button setTitleColor:otherBtnColor forState:UIControlStateNormal];
        }
    }
}

- (void)setOtherBtnFont:(NSInteger)otherBtnFont {
    
    for (id res in _bgView.subviews) {
        
        if ([res isKindOfClass:[UIButton class]]) {
            
            UIButton *button = (UIButton *)res;
            button.titleLabel.font = [UIFont systemFontOfSize:otherBtnFont];
        }
    }
}

- (void)setProFont:(NSInteger)proFont {
    
    _proLbl.font = [UIFont systemFontOfSize:proFont];
}

- (void)setCancelBtnFont:(NSInteger)cancelBtnFont {
    
    _cancelBtn.titleLabel.font = [UIFont systemFontOfSize:cancelBtnFont];
}

- (void)setDuration:(CGFloat)duration {
    
    self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:duration];
}

@end
